package org.kjtc.balanceController;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.kjtc.balanceEntity.MeterRecord;
import org.kjtc.balanceService.MeterRecordService;
import org.kjtc.controller.BaseController;
import org.kjtc.util.ExcelUtil;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
public class MeterRecordController extends BaseController {

	@Resource(name = "meterRecordService")
	private MeterRecordService meterRecordService;

	@RequestMapping(value = "/searchMeterRecord")
	@ResponseBody
	public Map<String, Object> getMeterRecords(MeterRecord meterRecord){

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "查询抄表记录开始");
		List<MeterRecord> meterRecordList = null;
		try {
			meterRecordList = meterRecordService.getMeterRecord(meterRecord);
		} catch (Exception e) {
			logger.error("查询抄表记录异常结束", e);
			e.printStackTrace();
		}
		map.put("meterRecordList", meterRecordList);
		logger.info(this.getUesrInfo().getUserName() + "查询抄表记录结束");
		meterRecord = null;
		return map;
	}

	@RequestMapping(value = "/searchMeterInfoAndRecord")
	@ResponseBody
	public Map<String, Object> getMeterInfoAndRecord(MeterRecord meterRecord){

		Map<String, Object> map = new HashMap<String, Object>();
		List<MeterRecord> meterRecords = null;
		try {
			meterRecords = meterRecordService.getMeterInfo(meterRecord);
			for (MeterRecord meterRecordContent : meterRecords) {
				meterRecordService.getLastMeterRecord(meterRecordContent);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		map.put("meterRecordList", meterRecords);
		return map;
	}

	@RequestMapping(value = "/searchMeterRecordDetalis")
	@ResponseBody
	public Map<String, Object> getMeterRecordDetalis(MeterRecord meterRecord){

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserID() + "查询抄表记录详情开始");
		List<MeterRecord> meterRecords = null;
		try {
			meterRecords = meterRecordService.getMeter(meterRecord);
		} catch (Exception e) {
			logger.error("查询抄表记录详情异常结束", e);
			e.printStackTrace();
		}
		map.put("meterRecords", meterRecords);
		meterRecord = null;
		logger.info(this.getUesrInfo().getUserID() + "查询抄表记录详情结束");
		return map;
	}

	@RequestMapping(value = "/addMeterRecord")
	@ResponseBody
	public Map<String, Object> addMeterRecord(String meterRecord) throws IOException {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserID() + "添加抄表记录开始");
		JSONArray meterRecordArray = JSONArray.fromObject(meterRecord);
		try {
			int exeCnt = meterRecordService.saveMeterRecord(meterRecordArray, this.getUesrInfo().getUserID());
			if (exeCnt > 0) {
				map.put("result", "Success");
			} else {
				map.put("result", "NotFound");
			}
		} catch (DuplicateKeyException ex) {
			String[] error = ex.getCause().getMessage().split("'");
			if ("PRIMARY".equals(error[3].trim())) {
				map.put("result", "MeterRecordDateNoNull");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
		}
		logger.info(this.getUesrInfo().getUserID() + "添加抄表记录结束");
		return map;
	}

	@RequestMapping(value = "/updateMeterRecord")
	@ResponseBody
	public Map<String, Object> updateMeterRecord(String meterRecord) throws IOException {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserID() + "修改抄表记录开始");
		JSONArray meterRecordArray = JSONArray.fromObject(meterRecord);
		try {
			int exeCnt = meterRecordService.updateMeterRecord(meterRecordArray, this.getUesrInfo().getUserID());
			if (exeCnt > 0) {
				map.put("result", "Success");
			} else {
				map.put("result", "NotFound");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
		}
		logger.info(this.getUesrInfo().getUserID() + "修改抄表记录结束");
		return map;
	}

	@RequestMapping(value = "/deleteMeterRecord")
	@ResponseBody
	public Map<String, Object> deleteMeterRecord(MeterRecord meterRecord, String id) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "抄表信息删除开始");
		String[] idList = id.split(",");
		meterRecord.setIDList(idList);
		int count;
		try {
			count = meterRecordService.deleteMeterRecord(meterRecord);
			meterRecordService.deleteMeterImg(meterRecord.getAddMeterRecordDate(), meterRecord.getChargingStationID());
			if (count > 0) {
				map.put("result", "Success");
			} else {
				map.put("result", "NotFound");
			}
		} catch (Exception e) {
			e.printStackTrace();
			map.put("result", "Error");
			logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "抄表信息删除异常:" + e.getMessage());
		}
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "抄表信息删除结束");
		meterRecord = null;
		return map;
	}

	@RequestMapping(value = "/addMeterRecordImg")
	@ResponseBody
	public Map<String, Object> addMeterRecordImg(@RequestParam(value="uploadFiles", required=false) MultipartFile[] files, String meterTime, String chargingStationID, String meterCode, String meterType, String avatar_data) throws IOException {

		String[] meterCodes = meterCode.split(",");
		String[] meterTypes = meterType.split(",");
		if(!"".equals(avatar_data)){
			avatar_data = avatar_data.substring(0, avatar_data.length()-1);
		}
		String[] avatar_datas = avatar_data.split(",,");
		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "上传抄表记录图片开始");
		try {
			String filePath = "";
			for (int i = 0; i < files.length; i++) {
				if(!"".equals(files[i])){
					filePath = meterRecordService.addMeterRecordImg(files[i], meterTime, chargingStationID, meterCodes[i], meterTypes[i], avatar_datas[i]);
				}
			}
			if (!"".equals(filePath)) {
				map.put("result", "Success");
			} else {
				map.put("result", "NotFound");
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(this.getUesrInfo().getUserName() + "上传抄表记录图片发生异常");
			map.put("result", "Error");
		}
		logger.info(this.getUesrInfo().getUserName() + "上传抄表记录图片结束");
		return map;
	}

	@RequestMapping(value = "/getMeterRecordImg")
	public void getMeterRecordImg(String meterCode, String meterTime, String chargingStationID, String meterType, HttpServletResponse response) throws Exception {
		meterRecordService.getMeterImg(meterCode, meterTime, chargingStationID, meterType, response);
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "importMeterRecord")
	@ResponseBody
	public Map<String, Object> importMeterRecord(@RequestParam(value="importExcle", required=false) MultipartFile file) {

		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "手抄记录导入");
		if (file != null && !file.isEmpty()) {
			try {
				List<MeterRecord> meterRecordRecordList = (List<MeterRecord>) ExcelUtil.importExcel(file.getInputStream(), "/static/json/meterRecordImportExcel.json", MeterRecord.class);
				if (meterRecordRecordList == null) {
					map.put("result", "JsonError");
					logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "导入失败，导入的JSON模板错误 或 不存在！");
				} else {
					int length = meterRecordRecordList.size();
					if (length > 0) {
						for(MeterRecord meterRecord : meterRecordRecordList) {
							meterRecord.setMeterMan(this.getUesrInfo().getUserName());
							meterRecord.setCreateUser(this.getUesrInfo().getUserID());
							meterRecord.setCreateDTTM(new Date());
						}
						int count = meterRecordService.importMeterRecord(meterRecordRecordList);
						map.put("result", "Success");
						map.put("count", count - length);
					} else {
						map.put("result", "NotFound");
						logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "导入失败，文件内没有可导入数据!");
					}
				}

			} catch (DataIntegrityViolationException e) {
				String[] error = e.getCause().getMessage().split("'");
				if("ChargingStationID".equals(error[1].trim())) {
					map.put("result", "ChargingStationIDNull");
				} else if("SubBranchCompanyID".equals(error[1].trim())) {
					map.put("result", "SubBranchCompanyIDNull");
				} else if("TeamID".equals(error[1].trim())) {
					map.put("result", "TeamIDNull");
				} else if("LineID".equals(error[1].trim())) {
					map.put("result", "LineIDNull");
				}
			} catch (Exception e) {
				map.put("result", "Error");
				logger.error(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "手抄记录文件【" +  file.getOriginalFilename() + "】导入异常：" + e.getMessage());
				e.printStackTrace();
			}
		} else {
			map.put("result", "NotFound");
			logger.info(this.getUesrInfo().getUserName() + "(" + this.getUesrInfo().getUserID() + ")：" + "导入失败，导入文件不存在!");
		}
		return map;
	}
}
